<script>
import { User, View } from "@element-plus/icons-vue";
import storage from "../utils/storage.js";
import util from "../utils/utils.js";
import router from "../router";
export default {
  name: "login",
  data() {
    return {
      userInfo: {
        userName: "",
        userPwd: "",
      },
      rules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        userPwd: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    async loadAsyncRouter() {
      try {
        const modules = import.meta.glob(`./system/*.vue`);
        let userInfo = storage.getItem("userInfo") || {};
        if (userInfo.token) {
          const { menuList } = await this.$api.getPermissionList();
          this.$store.commit("saveMenuList", menuList);
          let routes = util.generateRoute(menuList);
          routes.map((route) => {
            let url = `.${route.component}.vue`;
            route.component = modules[url];
            router.addRoute("home", route);
          });
        }
      } catch (error) {
        console.log("error", error);
      }
    },

    login() {
      this.$refs.userForm.validate((res) => {
        if (res) {
          this.$api.login(this.userInfo).then(async (data) => {
            this.$store.commit("saveUserInfo", data);
            console.log("87878979797");
            await this.loadAsyncRouter();
            this.$router.push("/welcome");
          });
        }
      });
    },
  },

  computed: {
    user() {
      return User;
    },
    view() {
      return View;
    },
  },
};
</script>

<template>
  <div class="login_wrapper">
    <div class="login_modal">
      <el-form :model="userInfo" :rules="rules" status-icon ref="userForm">
        <div class="login_title">登陆页</div>
        <el-form-item prop="userName">
          <el-input
            type="text"
            :prefix-icon="user"
            v-model="userInfo.userName"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input
            type="password"
            :prefix-icon="view"
            v-model="userInfo.userPwd"
          ></el-input>
        </el-form-item>
        <el-button type="primary" class="login_btn" @click="login"
          >登录</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* scoped防止外层样式污染，在这里可以去掉 */
.login_wrapper {
  background-color: #f9fcff;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  .login_modal {
    width: 500px;
    background-color: #fff;
    box-shadow: 0 0 10px 3px #c7c9cb4d;
    padding: 35px;
    .login_title {
      font-size: 35px;
      line-height: 1.5;
      text-align: center;
    }
    .login_btn {
      width: 100%;
    }
  }
}
</style>
